<!--
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-23 11:09:59
 * @LastEditTime: 2023-09-11 16:21:02
-->
<script lang="ts" setup name="IkPageFull">
import type { PropType } from 'vue'
import { defaultProps } from './props'
import useSettingsStore from '@/global/store/modules/settings'
import useUserStore from '@/global/store/modules/user'

const props = defineProps(defaultProps)
const emit = defineEmits<{
  'selection-change': [row: any]
  delete: [row: any]
  download: [row: any]
  addFunction: [form: any]
}>()
const pageData = defineModel({
  type: Object as PropType<{
    page: number
    rows: number
    [key: string]: any
  }>,
  default: () => undefined
})

if (!pageData.value?.page || !pageData.value?.rows) {
  pageData.value = {
    page: 1,
    rows: 15
  }
}

const handPageChange = (val: any) => {
  pageData.value = {
    ...pageData.value,
    ...val
  }
}

// 触发搜索
const handSearch = (val?: any) => {
  const obj = val?.type === 'click' ? {} : val
  pageData.value = {
    ...pageData.value,
    ...obj
  }
  props?.search?.({
    ...pageData.value
  })
}
// 不显示搜索栏并且需要首次查询
if (!props.showHeader && props.immediate)
  handSearch()

const userStore = useUserStore()
watch(() => userStore.organiza.select, () => {
  handSearch()
})

// 已选列表
const chooseList = ref([])
// 表格选中项变化
const handleSelectionChange = (val: any) => {
  chooseList.value = val
  emit('selection-change', val)
}
const dataLen = computed(() => chooseList.value.length || props.chooseLen)

const srotFields = ref(props.fields.map(fi => {
  if (!fi.fixed && (fi.tableSlot === 'operate' || !fi.key || fi.label === '操作'))
    fi.fixed = 'right'
  return fi
}))
const settingsStore = useSettingsStore()
const colorScheme = computed(() => settingsStore.settings?.app?.colorScheme)

const refTable = ref()
const refHeader = ref()
// 弹框对象
const refIkDialog = ref()
// 是否展示弹框
const visible = ref(false)
// 新增、修改
const editData: Ref<typeof props.formKey | undefined> = ref(undefined)
// 弹框标题
const dialogTitle = ref(props.title || '')
/**
 * @description: 打开弹框
 * @param {*} form
 * @return {*}
 */
const handAdd = (form: any) => {
  editData.value = form ? { ...form } : null
  if (props.title) {
    if (props.title.includes('新增') || props.title.includes('修改'))
      dialogTitle.value = form ? props.title.replace(/新增/g, '修改') : props.title.replace(/修改/g, '新增')

    else
      dialogTitle.value = form ? `修改${props.title}` : `新增${props.title}`
  }
  else {
    dialogTitle.value = form ? '修改' : '新增'
  }
  visible.value = true
}
/**
 * @description: 确定添加/修改数据
 * @param {*} form
 * @return {*}
 */
const sureAdd = (form: any) => {
  emit('addFunction', form)
  handSearch()
}

const needAutoForm = computed(() => props.fields.find(v => v.isEdit))
const autoWidthing = computed(() => props.autoWidth && (srotFields.value.length <= 4))

defineExpose({
  table: refTable,
  header: refHeader,
  chooseList,
  srotFields,
  pageData,
  dialog: refIkDialog,
  handAdd
})
</script>

<template>
  <!-- 标题 + 搜索表单 -->
  <IkPageHead
    v-if="showHeader"
    ref="refHeader"
    v-bind="{ ...$attrs, ...props }"
    v-model="srotFields"
    :form-slot="$slots"
    :loading="loading"
    :search="handSearch"
    :tab-id="tabId"
  >
    <template #headerLeft>
      <slot name="headerLeft"></slot>
    </template>
    <template #headerRight>
      <slot name="headerRight">
        <el-button
          v-if="needAutoForm"
          v-role="role"
          type="primary"
          @click="handAdd(null)"
        >
          新增
        </el-button>
      </slot>
    </template>
  </IkPageHead>
  <!-- 选中表格项 -->
  <div v-if="selection && showSelectBox" class="hand-selection" :class="{ select: dataLen }">
    <p class="choose">
      已选
      <span>
        <IkNumberDuration :value="dataLen" />
      </span>
      条
    </p>
    <div class="btn">
      <template v-if="!$slots.selectionRight">
        <IkSvgIcon
          name="icon-shanchu"
          show-bg
          :width="40"
          size="big"
          type="primary"
          @click="$emit('delete', chooseList)"
        />
        <IkSvgIcon
          name="icon-xiazai"
          show-bg
          :width="40"
          size="big"
          type="primary"
          @click="$emit('download', chooseList)"
        />
      </template>
      <slot v-else name="selectionRight"></slot>
    </div>
  </div>

  <!-- 自定义表格 -->
  <slot name="table">
    <IkPageTable
      ref="refTable"
      :page="pageData"
      v-bind="{ ...$attrs, ...props }"
      @page-change="handPageChange"
      @selection-change="handleSelectionChange"
    >
      <template v-for="item in srotFields" :key="item.key">
        <template v-if="item.show">
          <el-table-column
            v-if="!item.tableSlot"
            :prop="item.key"
            :align="item.align"
            :show-overflow-tooltip="{
              effect: colorScheme ?? 'light',
            }"
            :show-arrow="false"
            v-bind="{ ...item, ...$attrs, ...(props as any) }"
            :width="(autoWidthing && item.key && !item.label.includes('状态') && !item?.fixWidth && item.label !== '操作') ? null : item.width"
            :min-width="autoWidthing && item.key ? null : item.minWidth"
          />
          <el-table-column
            v-else
            :align="item.align"
            :show-overflow-tooltip="{
              effect: colorScheme ?? 'light',
            }"
            v-bind="{ ...item, ...$attrs, ...(props as any) }"
            :width="(autoWidthing && item.key && !item.label.includes('状态') && !item?.fixWidth && item.label !== '操作') ? null : item.width"
            :min-width="autoWidthing && item.key ? null : item.minWidth"
          >
            <template #default="columnData">
              <slot :name="item.tableSlot" :data="columnData"></slot>
            </template>
          </el-table-column>
        </template>
      </template>
    </IkPageTable>
  </slot>
  <!-- 新增修改 -->
  <IkDialog
    v-if="needAutoForm"
    ref="refIkDialog"
    v-bind="{ ...dialogProp }"
    v-model:visible="visible"
    :title="dialogTitle"
    :fields="fields"
    :size="dialogSize"
    :form-key="formKey"
    :edit-data="editData"
    @addFunction="sureAdd"
  />
</template>

<style lang="scss" scoped>
.hand-selection {
  height: 72px;
  background-color: var(--el-color-primary-light-9);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: absolute;
  top: 0;
  z-index: 0;
  width: 100%;
  transform: translateY(-100%);
  transition: transform 0.25s;

  &.select {
    transform: translateY(0);
    z-index: 3;
  }

  .choose {
    font-size: 20px;
    font-weight: 700;
    color: var(--ik-text-color);
    display: flex;
    align-items: center;

    span {
      color: var(--el-color-primary);
      padding: 0 8px;
    }
  }

  // @keyframes hand-selection {
  //   from {
  //     transform: translateY(-100%);
  //   }

  //  to {
  //      transform: translateY(0);
  //   }
  // }
}
</style>
